package com.gavindon.android.network

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.gavindon.android.R
import com.gavindon.android.base.MyApplication
import org.jetbrains.anko.matchParent
import java.lang.ref.WeakReference


@SuppressLint("StaticFieldLeak")
object LoadingHelper : LifecycleEventObserver {


    private lateinit var loadView: View
    fun createLoading() {
        val act = MyApplication.getCurActivity()


        val weakReference = WeakReference<Activity>(act)
        val frameDialog =
            weakReference.get()?.window?.findViewById<FrameLayout>(R.id.flyLoadingDialog)


        if (frameDialog != null) {
            loadView = frameDialog
        } else {
            val layoutInflater =
                act?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            loadView = layoutInflater.inflate(R.layout.loading_dialog_view, null, false)
            weakReference.get()?.window?.addContentView(
                loadView,
                FrameLayout.LayoutParams(matchParent, matchParent)
            )
        }
        loadView.visibility = View.VISIBLE
        loadView.isClickable = true
        loadView.isFocusable = true
    }

    fun cancelLoading() {
        if (this::loadView.isInitialized) {
            loadView.visibility = View.GONE
            loadView.isClickable = false
            loadView.clearFocus()
        }
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        if (event.targetState == Lifecycle.Event.ON_PAUSE.targetState) {
            cancelLoading()
        }
    }

}
